package com.qyhl.cloud.webtv.module_integral.wallet.money;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qyhl.cloud.webtv.module_integral.R;
import com.qyhl.cloud.webtv.module_integral.R2;
import com.qyhl.cloud.webtv.module_integral.app.IntegralApplication;
import com.qyhl.cloud.webtv.module_integral.common.IntergralUrl;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DESedeUtil;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.entity.intergral.MoneyBean;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * @author
 * @date 2019年4月1日10:42:25
 */
public class MoneyFragment extends BaseFragment {
    @BindView(R2.id.load_mask)
    LoadingLayout loadingMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;


    private final String tag = "MoneyFragmentTag";

    private List<MoneyBean> mdata;
    private CommonAdapter<MoneyBean> adapter;
    private int page = 1;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.inter_fragment_money, container, false);
    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected void create() {

    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {
        initView();
    }

    @Override
    protected void onVisible() {
        getData(page);
    }

    @Override
    protected void onHide() {

    }

    private void initView() {
        loadingMask.setStatus(LoadingLayout.Loading);
        loadingMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadingMask.setStatus(LoadingLayout.Loading);
                page = 1;
                getData(page);
            }
        });

        refresh.setEnableLoadMore(true);
        refresh.setEnableRefresh(true);
        //刷新中禁止操作
        refresh.setDisableContentWhenRefresh(true);
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        //下拉刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getData(page);
            }
        });

        //加载更多
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                getData(page);
            }
        });

        mdata = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(adapter = new CommonAdapter<MoneyBean>(getContext(),
                R.layout.inter_goldcoin_detail_layout, mdata) {
            @Override
            protected void convert(ViewHolder viewHolder, MoneyBean bean, int position) {
                viewHolder.setText(R.id.title, "金币兑换零钱");
                viewHolder.setText(R.id.describe, "主动发起" + bean.getCoin() + "金币兑换零钱");
                viewHolder.setText(R.id.time, bean.getDate());
                TextView detailed = viewHolder.getView(R.id.detailed);
                TextView glodText = viewHolder.getView(R.id.glodText);
                glodText.setText("元");
                if (bean.getMoney() > 0) {
                    detailed.setText("+" + bean.getMoney());
                    detailed.setTextColor(ContextCompat.getColor(getContext(), R.color.global_base));
                    glodText.setTextColor(ContextCompat.getColor(getContext(), R.color.global_base));
                } else {
                    detailed.setText(String.valueOf(bean.getMoney()));
                    detailed.setTextColor(ContextCompat.getColor(getContext(), R.color.global_black_lv0));
                    glodText.setTextColor(ContextCompat.getColor(getContext(), R.color.global_black_lv0));
                }

            }
        });

        getData(page);
    }

    private void getData(int page) {
        if (NetUtil.isNetworkAvalible(IntegralApplication.getApp())) {
            Map<String, String> map = DESedeUtil.encodeMapUrl(IntergralUrl.INTEGRAL_URL);
            JSONObject jsonObject = new JSONObject();
            try {
                String userName = CommonUtils.getInstance().getUserName();
                jsonObject.put("name", "myWallet");
                jsonObject.put("version", "2");
                jsonObject.put("username", userName);
                jsonObject.put("siteId", CommonUtils.getInstance().getSite());
                jsonObject.put("page", page);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            EasyHttp.post(map.get(DESedeUtil.URL))
                    .isDecrypt(true)
                    .decryptKet(map.get(DESedeUtil.CODEKEY))
                    .upBytes(DESedeUtil.encryptMode(map.get(DESedeUtil.CODEKEY),
                            jsonObject.toString()
                    ))
                    .execute(new SimpleCallBack<List<MoneyBean>>() {
                        @Override
                        public void onError(ApiException e) {
                            getDataError(TextUtils.isEmpty(e.getMessage()) ? "请求失败" : e.getMessage());
                        }

                        @Override
                        public void onSuccess(List<MoneyBean> moneyBeans) {
                            getDataSuccess(moneyBeans);
                        }
                    });


        } else {
            getDataError("无网络连接，请检查您的网络...");
        }
    }

    private void getDataSuccess(List<MoneyBean> data) {
        loadingMask.setStatus(LoadingLayout.Success);
        refresh.finishRefresh();
        refresh.finishLoadMore();

        if (data == null || data.isEmpty()) {
            if (page == 1) {
                loadingMask.setEmptyText("暂无内容");
                loadingMask.setEmptyImage(R.drawable.empty_content);
                loadingMask.setStatus(LoadingLayout.Empty);
            } else {
                Toasty.normal(getContext(), "没有更多了").show();
            }
        } else {
            if (page == 1) {
                mdata.clear();
            }
            mdata.addAll(data);
            adapter.notifyDataSetChanged();

            page++;
        }
    }

    private void getDataError(String message) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        if (page == 1) {
            loadingMask.setErrorText(message);
            loadingMask.setReloadButtonText("点击重试");
            loadingMask.setErrorImage(R.drawable.error_content);
            loadingMask.setStatus(LoadingLayout.Error);
        } else {
            Toasty.normal(getContext(), message).show();
        }
    }
}
